<template>
  <v-snackbar
    v-model="snackbar"
    multi-line
    :style="{ bottom: `90%` }"
    timeout="1000"
    @click="snackbar = false"
    :color="color"
  >
    <v-icon left>{{ text_ico }}</v-icon>
    {{ text }}
  </v-snackbar>
  <v-container class="container" fill-height>
    <v-row class="centered-row">
      <v-col cols="12" class="centered-col">
        <v-btn class="centered-btn" @click="openModal">创建文档/文件夹</v-btn>
      </v-col>
      <v-col cols="12">
        <v-text-field
          v-model="searchKeyword"
          label="搜索"
          @input="filterEntries"
        ></v-text-field>
        <div class="custom-breadcrumbs">
          <span v-for="(item, index) in bitems" :key="index">
            <v-chip
              class="ma-2"
              color="primary"
              @click="handleClick(item, index)"
              >{{ item.title }}</v-chip
            >
            <span v-if="index < bitems.length - 1">
              <v-icon icon="mdi-forward" color="blue"></v-icon
            ></span>
          </span>
        </div>

        <!-- 删除按钮（居右对齐） -->
        <v-row class="justify-end mt-4">
          <v-btn v-if="selectedItems.length > 0" @click="deleteSelectedItems"
            >删除选中项
          </v-btn>
        </v-row>
        <v-table>
          <thead>
            <tr>
              <th class="text-left">
                <v-checkbox
                  v-model="selectAll"
                  @change="toggleAllSelection"
                ></v-checkbox>
              </th>
              <th class="text-left">标题</th>
              <th class="text-left">时间</th>
              <th class="text-left">类型</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredDesserts" :key="item.name">
              <td>
                <v-checkbox v-model="selectedItems" :value="item"></v-checkbox>
              </td>
              <td @click="navigateToItem(item)">
                <template v-if="item.type === 0">
                  <v-icon color="blue">mdi-folder</v-icon>
                </template>
                <template v-else>
                  <span class="align-middle">
                    <img
                      :src="fontAwesomeIcon"
                      alt="Font Awesome Icon"
                      class="icon-image"
                    />
                  </span>
                </template>
                {{ item.name }}
              </td>
              <td @click="navigateToItem(item)">{{ item.date }}</td>
              <td @click="navigateToItem(item)">
                <template v-if="item.type === 0">
                  <v-chip class="ma-2" color="red" text-color="white">
                    文件夹
                  </v-chip>
                </template>
                <template v-else>
                  <span class="align-middle"> </span>
                  <v-chip class="ma-2" color="green" text-color="white">
                    文档
                  </v-chip>
                </template>
              </td>
            </tr>
          </tbody>
        </v-table>
      </v-col>
    </v-row>
    <!-- 模态框 -->
    <v-dialog v-model="modalOpen" persistent max-width="50%">
      <v-card>
        <v-card-title>
          <span>文章标题</span>
        </v-card-title>
        <v-card-text>
          <v-text-field
            v-model="inputValue"
            label="请输入标题"
            required
            :rules="titleRules"
            ref="titleField"
          ></v-text-field>
          <v-select
            label="Select"
            :items="['文档', '文件夹']"
            v-model="selectedItem"
          ></v-select>
        </v-card-text>
        <v-card-actions>
          <v-btn text @click="closeModal">关闭模态框</v-btn>
          <v-btn color="primary" @click="submitForm">提交</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<style>
.icon-image {
  width: 24px;
  /* 调整图片的宽度 */
  height: 24px;
  /* 调整图片的高度 */
}

.align-middle {
  display: inline-block;
  vertical-align: middle;
  /* 垂直居中对齐 */
}

.container {
  position: relative;
}

.centered-row {
  align-items: center;
}

.centered-col {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>

<script>
import axios from "axios";

export default {
  data: () => ({
    snackbar: false,
    text: ``,
    color: "success",
    text_ico: "mdi-check-circle",
    desserts: [],
    modalOpen: false, // 控制模态框的显示与隐藏
    inputValue: "", // 表单输入框的值
    searchKeyword: "",
    selectAll: false, // 控制全选复选框的状态
    selectedItems: [], // 已选中的表格行数据
    bitems: [
      {
        title: "文档",
        disabled: false,
        href: "/md",
      },
    ],
    selectedItem: "文件夹",
    titleRules: [(value) => !!value || "标题不能为空"],
    fontAwesomeIcon: "",
  }),
  methods: {
    openModal() {
      this.modalOpen = true; // 打开模态框
    },
    closeModal() {
      this.modalOpen = false; // 关闭模态框
    },
    alertmsg(text, ico, color) {
      console.log(text, ico, color);
      if (ico === undefined) {
        ico = "mdi-check-circle";
      }
      if (color === undefined) {
        color = "success";
      }

      this.color = color;
      this.text = text;
      this.text_ico = ico;
      this.snackbar = true;
      console.log(text, ico, color);
    },
    submitForm() {
      if (this.$refs.titleField.validate() && this.inputValue.length > 0) {
        let mdType = "";
        let mdlevel = this.bitems.length;
        if (this.selectedItem === "文件夹") {
          mdType = 0;
        } else {
          mdType = 1;
        }
        const parent = this.bitems.slice(-1)[0]["title"];
        axios
          .post("/api/md/add", {
            name: this.inputValue,
            type: mdType,
            level: mdlevel,
            parent: parent,
          }) // 发送GET请求到后端API
          .then((response) => {
            this.getProject();
            console.log(response.data);
            this.alertmsg(response.data.msg);
          })
          .catch((error) => {
            // 处理请求错误
            this.alertmsg(error.response.data.msg, "mdi-cancel", "error");

            console.error(error);
          });
        this.closeModal(); // 提交后关闭模态框
      } else {
        // 校验未通过，给出提示信息
        console.log("标题不能为空");
      }
    },
    filterEntries() {
      // 当搜索框输入内容时触发过滤操作
      // 这里只是修改了搜索关键字，computed 属性会自动触发重新计算 filteredDesserts
    },
    toggleAllSelection() {
      // 全选复选框状态改变时触发
      if (this.selectAll) {
        this.selectedItems = [...this.filteredDesserts];
      } else {
        this.selectedItems = [];
      }
    },
    isSelected(item) {
      // 检查一个项目是否被选中
      return this.selectedItems.includes(item);
    },
    deleteSelectedItems() {
      // 删除选中项按钮点击事件处理
      this.desserts = this.desserts.filter(
        (item) => !this.selectedItems.includes(item)
      );
      axios
        .post("/api/md/del", { data: this.selectedItems }) // 发送GET请求到后端API
        .then((response) => {
          this.alertmsg(response.data.msg);
        })
        .catch((error) => {
          // 处理请求错误
          this.alertmsg(error.response.data.msg, "mdi-cancel", "error");
        });
      this.getProject();
    },
    getProject() {
      axios
        .post("/api/md/project", {
          level: this.bitems.length,
          parent: this.bitems[this.bitems.length - 1]["title"],
        }) // 发送GET请求到后端API
        .then((response) => {
          console.log(response);
          this.desserts = response.data.data;
        })
        .catch((error) => {
          // 处理请求错误
          this.alertmsg(error.response.data.msg, "mdi-cancel", "error");
          setTimeout(() => {
            this.snackbar = false;
            this.$router.push("/login"); // 将路由跳转放在关闭 Snackbar 后
          }, 1000);
        });
    },
    handleClick(item, index) {
      const proxyString = this.bitems;

      if (index >= 0 && index < proxyString.length) {
        proxyString.splice(index + 1, proxyString.length - index - 1);
      }
      this.getProject();
      // 执行其他点击处理逻辑
    },
    navigateToItem(item) {
      if (item.type === 1) {
        this.$router.push({ name: "mdedit", params: { itemName: item.name } });
        // window.open("/md/" + item.name, "_blank");
      } else {
        const data = {
          title: item.name,
          disabled: false,
          href: () => {
            // 在此处编写相应的点击处理逻辑
            console.log("点击了 /md");
          },
        };
        const proxyString = this.bitems;
        const isInArray = proxyString.some((obj) => {
          return JSON.stringify(obj) === JSON.stringify(data);
        });
        if (!isInArray) {
          this.bitems.push(data);
          this.getProject();
        }
      }
      // 调用编程式导航方法，根据 item.name 进行导航
    },
    loadSvgIcon() {
      // 导入 SVG 图标
      const svgData = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M593.8 59.1H46.2C20.7 59.1 0 79.8 0 105.2v301.5c0 25.5 20.7 46.2 46.2 46.2h547.7c25.5 0 46.2-20.7 46.1-46.1V105.2c0-25.4-20.7-46.1-46.2-46.1zM338.5 360.6H277v-120l-61.5 76.9-61.5-76.9v120H92.3V151.4h61.5l61.5 76.9 61.5-76.9h61.5v209.2zm135.3 3.1L381.5 256H443V151.4h61.5V256H566z"/></svg>`;
      const base64Data = btoa(svgData);
      this.fontAwesomeIcon = `data:image/svg+xml;base64,${base64Data}`;
    },
  },
  computed: {
    filteredDesserts() {
      // 根据搜索关键字过滤表格数据
      return this.desserts.filter((item) => {
        return item.name
          .toLowerCase()
          .includes(this.searchKeyword.toLowerCase());
      });
    },
  },
  created() {
    this.getProject();
    this.loadSvgIcon();
  },
};
</script>
